#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
MySQL角色管理器
负责角色的创建、保存和加载（基于MySQL数据库）
"""

import logging
from datetime import datetime
from typing import List, Optional, Dict, Any, Tuple
from database import db_manager, Character, Account, CharacterClass, CharacterStatus
from database.models import Character as DBCharacter

class MySQLCharacterManager:
    """
    基于MySQL的角色管理器
    """
    
    def __init__(self, account_id: int = 1):
        """
        初始化角色管理器
        
        Args:
            account_id: 当前账号ID
        """
        self.account_id = account_id
        self.current_character: Optional[Character] = None
        self.logger = logging.getLogger(__name__)
        
        # 测试数据库连接
        if not db_manager.test_connection():
            raise Exception("数据库连接失败")
    
    def create_character(self, name: str, character_class: str = "战士") -> Tuple[bool, str, Optional[Character]]:
        """
        创建新角色
        
        Args:
            name: 角色名称
            character_class: 角色职业
            
        Returns:
            (成功标志, 消息, 角色对象)
        """
        try:
            # 检查角色名是否已存在（同账号下）
            existing_char = self.get_character_by_name(name)
            if existing_char:
                return False, f"角色名 '{name}' 已存在", None
            
            # 检查账号角色数量限制
            print(f"DEBUG: 创建角色时的 self.account_id = {self.account_id}")
            characters = self.get_characters_by_account(self.account_id)
            print(f"DEBUG: 当前账号已有角色数量 = {len(characters)}")
            if len(characters) >= 10:  # 最大10个角色
                return False, "角色数量已达上限（10个）", None
            
            # 验证职业
            try:
                # 处理职业名称映射（兼容英文和中文输入）
                class_mapping = {
                    'warrior': '战士',
                    'mage': '法师', 
                    'archer': '弓箭手',
                    'assassin': '刺客',
                    'priest': '牧师',
                    '盗贼': '刺客'  # 兼容性映射
                }
                
                # 如果是英文名或需要映射的名称，转换为中文名
                if character_class in class_mapping:
                    character_class = class_mapping[character_class]
                
                char_class_enum = CharacterClass(character_class)
            except ValueError:
                return False, f"无效的角色职业: {character_class}", None
            
            # 创建角色
            now = datetime.now()
            insert_query = """
                INSERT INTO characters 
                (account_id, name, character_class, level, exp, hp, mp, attack, defense, speed, 
                 status, created_at, last_active)
                VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
            """
            
            print(f"DEBUG: 执行INSERT时的 self.account_id = {self.account_id}")
            char_id = db_manager.execute_insert(insert_query, (
                self.account_id, name, character_class, 1, 0, 100, 50, 10, 5, 8,
                CharacterStatus.IDLE.value, now, now
            ))
            
            # 创建初始挂机记录
            self._create_initial_idle_record(char_id)
            
            # 获取创建的角色
            character = self.get_character_by_id(char_id)
            
            self.logger.info(f"角色 '{name}' 创建成功，ID: {char_id}")
            return True, f"角色 '{name}' 创建成功", character
            
        except Exception as e:
            self.logger.error(f"创建角色失败: {e}")
            return False, f"创建角色失败: {str(e)}", None
    
    def _create_initial_idle_record(self, char_id: int):
        """
        为新角色创建初始挂机记录
        
        Args:
            char_id: 角色ID
        """
        try:
            # 获取默认挂机地点（新手村）
            location_query = "SELECT id FROM idle_locations WHERE min_level <= 1 ORDER BY min_level LIMIT 1"
            locations = db_manager.execute_query(location_query)
            
            if locations:
                location_id = locations[0]['id']
                
                # 创建挂机记录
                insert_query = """
                    INSERT INTO idle_records (character_id, location_id, start_time, status)
                    VALUES (%s, %s, %s, %s)
                """
                
                db_manager.execute_insert(insert_query, (
                    char_id, location_id, datetime.now(), 'active'
                ))
                
                self.logger.info(f"为角色 {char_id} 创建初始挂机记录")
                
        except Exception as e:
            self.logger.error(f"创建初始挂机记录失败: {e}")
    
    def get_character_by_id(self, character_id: int) -> Optional[Character]:
        """
        根据ID获取角色
        
        Args:
            character_id: 角色ID
            
        Returns:
            角色对象或None
        """
        try:
            query = """
                SELECT c.*, il.name as idle_location_name
                FROM characters c
                LEFT JOIN idle_records ir ON c.id = ir.character_id AND ir.status = 'active'
                LEFT JOIN idle_locations il ON ir.location_id = il.id
                WHERE c.id = %s AND c.account_id = %s
            """
            
            result = db_manager.execute_query(query, (character_id, self.account_id))
            
            if result:
                return self._create_character_from_db(result[0])
            
            return None
            
        except Exception as e:
            self.logger.error(f"获取角色失败: {e}")
            return None
    
    def get_character_by_name(self, name: str) -> Optional[Character]:
        """
        根据名称获取角色（同账号下）
        
        Args:
            name: 角色名称
            
        Returns:
            角色对象或None
        """
        try:
            query = """
                SELECT c.*, il.name as idle_location_name
                FROM characters c
                LEFT JOIN idle_records ir ON c.id = ir.character_id AND ir.status = 'active'
                LEFT JOIN idle_locations il ON ir.location_id = il.id
                WHERE c.name = %s AND c.account_id = %s
            """
            
            result = db_manager.execute_query(query, (name, self.account_id))
            
            if result:
                return self._create_character_from_db(result[0])
            
            return None
            
        except Exception as e:
            self.logger.error(f"获取角色失败: {e}")
            return None
    
    def get_all_characters(self) -> List[Character]:
        """
        获取当前账号的所有角色
        
        Returns:
            角色列表
        """
        try:
            query = """
                SELECT c.*, il.name as idle_location_name
                FROM characters c
                LEFT JOIN idle_records ir ON c.id = ir.character_id AND ir.status = 'active'
                LEFT JOIN idle_locations il ON ir.location_id = il.id
                WHERE c.account_id = %s
                ORDER BY c.created_at DESC
            """
            
            result = db_manager.execute_query(query, (self.account_id,))
            
            characters = []
            for row in result:
                character = self._create_character_from_db(row)
                if character:
                    characters.append(character)
            
            return characters
            
        except Exception as e:
            self.logger.error(f"获取角色列表失败: {e}")
            return []
    
    def get_characters_by_account(self, account_id: int) -> List[Character]:
        """
        根据账号ID获取角色列表
        
        Args:
            account_id: 账号ID
            
        Returns:
            角色列表
        """
        try:
            query = """
                SELECT c.*, il.name as idle_location_name
                FROM characters c
                LEFT JOIN idle_records ir ON c.id = ir.character_id AND ir.status = 'active'
                LEFT JOIN idle_locations il ON ir.location_id = il.id
                WHERE c.account_id = %s
                ORDER BY c.created_at DESC
            """
            
            result = db_manager.execute_query(query, (account_id,))
            
            characters = []
            for row in result:
                character = self._create_character_from_db(row)
                if character:
                    characters.append(character)
            
            return characters
            
        except Exception as e:
            self.logger.error(f"获取角色列表失败: {e}")
            return []
    
    def select_character(self, character_id: int) -> Tuple[bool, str]:
        """
        选择当前角色
        
        Args:
            character_id: 角色ID
            
        Returns:
            (成功标志, 消息)
        """
        character = self.get_character_by_id(character_id)
        if not character:
            return False, "角色不存在"
        
        self.current_character = character
        return True, f"已选择角色: {character.name}"
    
    def delete_character(self, character_id: int) -> Tuple[bool, str]:
        """
        删除角色
        
        Args:
            character_id: 角色ID
            
        Returns:
            (成功标志, 消息)
        """
        try:
            character = self.get_character_by_id(character_id)
            if not character:
                return False, "角色不存在"
            
            # 检查角色是否在战斗中
            if character.status == CharacterStatus.BATTLE:
                return False, "角色正在战斗中，无法删除"
            
            # 先删除相关的idle_records记录
            delete_idle_query = "DELETE FROM idle_records WHERE character_id = %s"
            db_manager.execute_update(delete_idle_query, (character_id,))
            
            # 删除角色记录
            delete_query = "DELETE FROM characters WHERE id = %s AND account_id = %s"
            affected_rows = db_manager.execute_update(delete_query, (character_id, self.account_id))
            
            if affected_rows > 0:
                # 如果删除的是当前角色，清空当前角色
                if self.current_character and self.current_character.char_id == character_id:
                    self.current_character = None
                
                self.logger.info(f"角色 '{character.name}' 已删除")
                return True, f"角色 '{character.name}' 已删除"
            else:
                return False, "删除失败"
                
        except Exception as e:
            self.logger.error(f"删除角色失败: {e}")
            return False, f"删除角色失败: {str(e)}"
    
    def update_character(self, character: Character) -> bool:
        """
        更新角色数据
        
        Args:
            character: 角色对象
            
        Returns:
            是否成功
        """
        try:
            update_query = """
                UPDATE characters 
                SET level = %s, exp = %s, hp = %s, mp = %s, attack = %s, defense = %s, 
                    speed = %s, status = %s, last_active = %s
                WHERE id = %s AND account_id = %s
            """
            
            affected_rows = db_manager.execute_update(update_query, (
                character.level, character.exp, character.hp, character.mp,
                character.attack, character.defense, character.speed,
                character.status.value if isinstance(character.status, CharacterStatus) else character.status,
                datetime.now(), character.char_id, self.account_id
            ))
            
            return affected_rows > 0
            
        except Exception as e:
            self.logger.error(f"更新角色失败: {e}")
            return False
    
    def _create_character_from_db(self, row: Dict[str, Any]) -> Optional[Character]:
        """
        从数据库记录创建角色对象
        
        Args:
            row: 数据库记录
            
        Returns:
            角色对象
        """
        try:
            character = Character(
                char_id=row['id'],  # 数据库中的主键是id
                account_id=row['account_id'],
                name=row['name'],
                char_class=CharacterClass(row['character_class']),
                level=row['level'],
                exp=row['exp'],
                hp=row['hp'],
                mp=row['mp'],
                attack=row['attack'],
                defense=row['defense'],
                speed=row['speed'],
                status=CharacterStatus(row['status']),
                created_at=row['created_at'],
                last_active=row['last_active']
            )
            
            # 设置挂机相关属性（兼容旧代码）
            character.is_idle = (character.status == CharacterStatus.IDLE)
            character.is_in_battle = (character.status == CharacterStatus.BATTLE)
            character.idle_location = row.get('idle_location_name', '新手村')
            character.exp_to_next_level = character.get_exp_for_next_level()
            
            # 兼容旧的ID字段
            character.id = str(character.char_id)
            
            return character
            
        except Exception as e:
            self.logger.error(f"创建角色对象失败: {e}")
            return None
    
    def get_character_classes(self) -> List[str]:
        """
        获取可选的角色职业
        
        Returns:
            职业列表
        """
        return [cls.value for cls in CharacterClass]
    
    def get_character_stats(self) -> Dict[str, Any]:
        """
        获取角色统计信息
        
        Returns:
            统计信息字典
        """
        try:
            characters = self.get_all_characters()
            total_characters = len(characters)
            max_level = max([char.level for char in characters]) if characters else 0
            
            class_counts = {}
            for character in characters:
                class_name = character.char_class.value if isinstance(character.char_class, CharacterClass) else character.char_class
                class_counts[class_name] = class_counts.get(class_name, 0) + 1
            
            return {
                'total_characters': total_characters,
                'max_level': max_level,
                'class_distribution': class_counts,
                'current_character': self.current_character.name if self.current_character else None,
                'account_id': self.account_id
            }
            
        except Exception as e:
            self.logger.error(f"获取统计信息失败: {e}")
            return {
                'total_characters': 0,
                'max_level': 0,
                'class_distribution': {},
                'current_character': None,
                'account_id': self.account_id
            }
    
    def set_account_id(self, account_id: int):
        """
        设置当前账号ID
        
        Args:
            account_id: 账号ID
        """
        print(f"DEBUG: set_account_id 接收到的值 = {account_id}, 类型: {type(account_id)}")
        self.account_id = account_id
        self.current_character = None  # 切换账号时清空当前角色